package my.suveng.alarm;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import my.suveng.alarm.de.AlarmEvent;
import my.suveng.alarm.dependency.AbstractAlarmEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.util.ObjectUtils;

/**
 * spring 事件推送
 * @author suwenguang
 * @date 2020/11/5 9:27 上午
 * @since 1.0
 */
public class EventPublisher {

    private static ApplicationContext applicationContext;

    private static ApplicationContext rootContext = null;

    /**
     * 发送告警信息
     */
    public static void alarm(AbstractAlarmEvent alarmEvent) {
        ApplicationContext root = root();
        root.publishEvent(alarmEvent);
    }

    /**
     * 发送告警信息
     */
    public static void alarm(String content) {
        ApplicationContext root = root();
        root.publishEvent(new AlarmEvent(content));
    }

    /**
     * 获取root context
     * @return {@link ApplicationContext}
     */
    private static ApplicationContext root() {
        if (!ObjectUtils.isEmpty(rootContext)) {
            return rootContext;
        }

        ApplicationContext root = SpringUtil.getApplicationContext();
        while (!ObjectUtils.isEmpty(root.getParent())) {
            root = root.getParent();
        }

        if (ObjectUtils.isEmpty(rootContext)) {
            rootContext = root;
        }

        if (ObjectUtil.isEmpty(root)) {
            throw new RuntimeException(StrUtil.format("spring context is null , check your spring configuration"));
        }
        return root;
    }
}
